package com.revenant.driver.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apkfuns.logutils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.nukc.stateview.StateView;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.luck.picture.lib.tools.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.revenant.driver.App;
import com.revenant.driver.R;
import com.revenant.driver.adapter.AreaCitySelectItemAdapter;
import com.revenant.driver.adapter.AreaSelectItemAdapter;
import com.revenant.driver.adapter.AreaSelectItemEndAdapter;
import com.revenant.driver.adapter.Driver.LianWangAdapter;
import com.revenant.driver.adapter.PhoneSelectAdapter;
import com.revenant.driver.base.BaseFragment;
import com.revenant.driver.bean.Driver.LiangWangSecondBean;
import com.revenant.driver.bean.LianWangNewBean;
import com.revenant.driver.bean.OnlinePhoneBean;
import com.revenant.driver.bean.Selectareabean;
import com.revenant.driver.ui.activity.DriverGoodsDetailActivity;
import com.revenant.driver.ui.activity.LoginActivity;
import com.revenant.driver.ui.activity.NewImproveDriverInfoaActivity;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.revenant.driver.bean.Message.Driver_RenZheng_6;
import static com.revenant.driver.bean.Message.Driver_RenZheng_7;
import static com.revenant.driver.bean.Message.Driver_RenZheng_8;
import static com.revenant.driver.utils.Constants.Area_City;
import static com.revenant.driver.utils.Constants.Area_Provice;
import static com.revenant.driver.utils.Constants.Look_LianWang;
import static com.revenant.driver.utils.Constants.Look_LianWang_New;

/**
 * @ProjectName: Driver
 * @Package: com.revenant.driver.ui.fragment
 * @ClassName: DriverFragment
 * @Description: java类作用描述
 * @Author: Revenant
 * @CreateDate: 2020-02-07 14:49
 * @UpdateUser: 更新者
 * @UpdateDate: 2020-02-07 14:49
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class DriverLianWangFragment extends BaseFragment {
    @BindView(R.id.search_start)
    TextView searchStart;
    @BindView(R.id.search_end)
    TextView searchEnd;
    @BindView(R.id.search_more)
    TextView searchMore;
    @BindView(R.id.show_search)
    LinearLayout showSearch;
    private LianWangAdapter itemAdapter;

    @BindView(R.id.start_place)
    TextView startPlace;
    @BindView(R.id.end_place)
    TextView endPlace;
    @BindView(R.id.jiehuocheliangrecy)
    RecyclerView jiehuocheliangrecy;
    @BindView(R.id.jiehuocheliangsmart)
    SmartRefreshLayout jiehuocheliangsmart;
    @BindView(R.id.loadLayout)
    LinearLayout loadLayout;

    private int pagernum = 1;

    CityPickerView mPickerstart = new CityPickerView();

    CityPickerView mPickerend = new CityPickerView();
    private PhoneSelectAdapter phoneSelectAdapter;

    private String starttext = "";
    private String endctext = "";

    private String startdefaulttext = "";
    private String enddeaufttext = "";


    private String startCode = "";
    private String startProCode = "";
    private String endProCode = "";
    private String endCode = "";
    private String searchinfo = "";


    private PopupWindow popstartwindow;
    private PopupWindow popendwindow;
    private PopupWindow popsearch;


    private int priviceselectcount = 0;
    private int privicepre = -1;
    private int priviceendpre = -1;
    private int cityselectcount = 0;

    private int priviceendselectcount = 0;
    private int cityendselectcount = 0;

    private AreaSelectItemAdapter privicestartAdapter;
    private AreaCitySelectItemAdapter citystartAdapter;


    private AreaSelectItemEndAdapter priviceendAdapter;
    private AreaCitySelectItemAdapter cityendAdapter;
    private Context context;


    private final int Update_car = 101;
    private int SecondTest = 5000;
    private int SecondTestdelay = 500;
    private int MaxPushCount = 3;
    private int pushcountindex = 0;
    private Timer timer;

    protected boolean isVisibleshow;
    private int typejiazai = 1;
    private int scrolltype = 0;
    private AlertDialog alertDialog;
    private long start;


    @Override
    protected int setLayoutId() {
        return R.layout.fragment_driver_lianwang;
    }

    public static DriverLianWangFragment newInstance(String param1) {
        DriverLianWangFragment fragment = new DriverLianWangFragment();
        Bundle args = new Bundle();
        args.putString(param1, param1);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initView() {
        mStateView = StateView.inject(loadLayout);
        mPickerstart.init(getActivity());
        mPickerend.init(getActivity());
        itemAdapter = new LianWangAdapter();

        itemAdapter.openLoadAnimation(BaseQuickAdapter.HEADER_VIEW);
        itemAdapter.isFirstOnly(false);

        jiehuocheliangrecy.setLayoutManager(new LinearLayoutManager(getActivity()));
        jiehuocheliangrecy.setAdapter(itemAdapter);
        jiehuocheliangsmart.autoRefresh();

        jiehuocheliangrecy.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("定时器newState", String.valueOf(newState));
//                0 静止没有滚动,1 正在被外部拖拽,一般为用户正在用手指滚动 ,2 自动滚动
                if (newState == 0) {

                    /*排序 拨打电话，以及跳出页面进行，滑动暂停*/
//                    1，滑动
//                      2.拨打电话
//                    3.弹出页面
                    scrolltype = 1;
                    start = System.currentTimeMillis();
                } else {
                    scrolltype = 2;
                }
            }

            @Override
            public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("定时器dx", String.valueOf(dx));
                Log.d("定时器dy", String.valueOf(dy));
                /*y>0,向上滑动*/
                /*y<0,向下滑动*/
            }
        });

        initArea();

        mStateView.setOnRetryClickListener(new StateView.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                //do something
                jiehuocheliangsmart.autoRefresh();
            }
        });
        itemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.shengyu:
//                        if (SPUtils.getAccounId(getActivity()) == 0) {
//                            Intent intent = new Intent();
//                            intent.setClass(getActivity(), LoginActivity.class);
//                            startActivity(intent);
//                        } else {

                        scrolltype = 2;
                        String phonenumber = itemAdapter.getData().get(position).getPhonenumber();
                        if (phonenumber != null && !phonenumber.isEmpty()) {
                            String[] split = phonenumber.split(" ");
                            List<OnlinePhoneBean> phoneBeanList = new ArrayList<>();
                            for (int i = 0; i < split.length; i++) {
                                OnlinePhoneBean onlinePhoneBean = new OnlinePhoneBean();
                                onlinePhoneBean.setPhonenum(split[i]);
                                phoneBeanList.add(onlinePhoneBean);
                            }
                            getDriverEmpty(phoneBeanList);
//                            }


//                            App applicationContext = App.getApplication();
//                            int userStatus = applicationContext.getUserStatus();
//                            switch (userStatus) {
//                                case 5:
//                                    String phonenumber = itemAdapter.getData().get(position).getPhonenumber();
//                                    if (phonenumber != null && !phonenumber.isEmpty()) {
//                                        String[] split = phonenumber.split(" ");
//                                        List<OnlinePhoneBean> phoneBeanList = new ArrayList<>();
//                                        for (int i = 0; i < split.length; i++) {
//                                            OnlinePhoneBean onlinePhoneBean = new OnlinePhoneBean();
//                                            onlinePhoneBean.setPhonenum(split[i]);
//                                            phoneBeanList.add(onlinePhoneBean);
//                                        }
//                                        getDriverEmpty(phoneBeanList);
//                                    }
//                                    break;
//                                case 6:
//                                    ToastUtils.s(getContext(), Driver_RenZheng_6);
//                                    Intent intent6 = new Intent();
//                                    intent6.setClass(getActivity(), NewImproveDriverInfoaActivity.class);
//                                    startActivity(intent6);
//                                    break;
//                                case 7:
//                                    ToastUtils.s(getContext(), Driver_RenZheng_7);
//                                    break;
//                                case 8:
//                                    ToastUtils.s(getContext(), Driver_RenZheng_8);
//                                    Intent intent8 = new Intent();
//                                    intent8.setClass(getActivity(), NewImproveDriverInfoaActivity.class);
//                                    startActivity(intent8);
//
//
//                                    break;
//                                default:
//                            }
                        }
                        break;
                }
            }
        });
        itemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtils.getAccounId(getActivity()) == 0) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    App applicationContext = App.getApplication();
                    int userStatus = applicationContext.getUserStatus();
                    switch (userStatus) {
                        case 5:
                            scrolltype = 2;
                            Bundle bundle = new Bundle();
                            bundle.putInt("goods_type", 2);
                            bundle.putInt("goods_auto", 3);
                            bundle.putString("goods_id", String.valueOf(itemAdapter.getData().get(position).getId()));
                            Intent intent = new Intent();
                            intent.putExtras(bundle);
                            intent.setClass(getActivity(), DriverGoodsDetailActivity.class);
                            startActivity(intent);
                            break;
                        case 6:
                            ToastUtils.s(getContext(), Driver_RenZheng_6);
                            Intent intent6 = new Intent();
//                            intent6.setClass(getActivity(), DriverRenZhengOneActivity.class);
                            intent6.setClass(getActivity(), NewImproveDriverInfoaActivity.class);
                            startActivity(intent6);
                            break;
                        case 7:
                            ToastUtils.s(getContext(), Driver_RenZheng_7);
                            break;
                        case 8:
                            ToastUtils.s(getContext(), Driver_RenZheng_8);
                            Intent intent8 = new Intent();
//                            intent8.setClass(getActivity(), DriverRenZhengOneActivity.class);
                            intent8.setClass(getActivity(), NewImproveDriverInfoaActivity.class);
                            startActivity(intent8);
                            break;
                        default:
                    }
                }
            }
        });
    }

    @Override
    public void initData() {
        jiehuocheliangsmart.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pagernum++;
                searchContent(startCode, endCode, searchinfo, startProCode, endProCode);

                jiehuocheliangsmart.finishLoadMore(true);//加载完成
            }
        });
        //刷新
        jiehuocheliangsmart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                Log.d("定时器", String.valueOf(typejiazai));

//                if (timer!=null&&typejiazai>1){
//                    timer.cancel();
//                    Log.d("定时器","取消onRefresh");
//                }
                itemAdapter.setNewData(null);
                pagernum = 1;
                searchContent(startCode, endCode, searchinfo, startProCode, endProCode);

                jiehuocheliangsmart.finishRefresh(true);//刷新完成
            }
        });
    }


    private void initDataRecyclerview(String setoutcity, String destinationcity, String keysWord, String setoutprovince, String destinationprovince) {
        if (SPUtils.getAccounId(getActivity()) == 0) {
            OkGo.<String>get(Look_LianWang_New)
//                    .params("pageNum", pagernum)
                    .params("setoutprovince", setoutprovince)
                    .params("setoutcity", setoutcity)
                    .params("destinationprovince", destinationprovince)
                    .params("destinationcity", destinationcity)
                    .params("keysWord", keysWord)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            LianWangNewBean shipperPublishedBean = GsonUtil.parseJsonWithGson(response.body(), LianWangNewBean.class);

                            if (shipperPublishedBean.getCode().equals("0")) {
                                if (shipperPublishedBean.getData() != null) {
                                    if (shipperPublishedBean.getData().size() > 0) {
                                        itemAdapter.setNewData(shipperPublishedBean.getData());
                                    }
                                }
//                                int pageNum = shipperPublishedBean.getData().getPageNum();
//                                int pages = shipperPublishedBean.getData().getPages();
//                                if (pageNum == 1) {


//
//                                } else if (pageNum <= pages) {
//                                    itemAdapter.addData(shipperPublishedBean.getData().getResult());
//                                } else {
//                                    itemAdapter.loadMoreEnd();
//                                }


                            } else {
                                itemAdapter.loadMoreFail();
                            }
                            mStateView.showContent();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            mStateView.showRetry();
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }
                    });

        } else {
            showSearch.setVisibility(View.VISIBLE);
            OkGo.<String>get(Look_LianWang_New)
//
//                    .params("id", SPUtils.getAccounId(getActivity()))
//                    .params("maxId", pagernum)
                    .params("setoutprovince", setoutprovince)
                    .params("setoutcity", setoutcity)
                    .params("destinationprovince", destinationprovince)
                    .params("destinationcity", destinationcity)
                    .params("keysWord", keysWord)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            LianWangNewBean shipperPublishedBean = GsonUtil.parseJsonWithGson(response.body(), LianWangNewBean.class);
                            if (shipperPublishedBean.getData() != null) {
//                                int pageNum = shipperPublishedBean.getData().getPageNum();
//                                int pages = shipperPublishedBean.getData().getPages();
                                if (shipperPublishedBean.getCode().equals("0")) {
//                                    if (pageNum == 1) {

                                    if (shipperPublishedBean.getData() != null) {
                                        if (shipperPublishedBean.getData().size() > 0) {
                                            itemAdapter.setNewData(shipperPublishedBean.getData());
                                        }
                                    }


//                                    } else if (pageNum <= pages) {
//                                        itemAdapter.addData(shipperPublishedBean.getData());
//                                    } else {
//                                        itemAdapter.loadMoreEnd();
//                                    }

//                                    if (timer==null&&getUserVisibleHint()&&typejiazai>1){
//                                        timerTest();
//                                    }

                                } else {
                                    itemAdapter.loadMoreFail();
                                }

                            }
                            mStateView.showContent();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            mStateView.showRetry();
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }
                    });
        }

    }

    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        getContext().startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
//        jiehuocheliangsmart.autoRefresh();
    }

    private void getDriverEmpty(List<OnlinePhoneBean> phoneBeanList) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = getLayoutInflater().inflate(R.layout.phone_select, null);
        RecyclerView type = view.findViewById(R.id.recyclerview);
        ImageView cancel = view.findViewById(R.id.cancel);

        phoneSelectAdapter = new PhoneSelectAdapter();
        phoneSelectAdapter.setNewData(phoneBeanList);
        type.setLayoutManager(new LinearLayoutManager(getContext()));
        type.setAdapter(phoneSelectAdapter);

        builder.setView(view);
        alertDialog = builder.show();
        alertDialog.setCanceledOnTouchOutside(false);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialog.dismiss();
                scrolltype = 1;
            }
        });
        phoneSelectAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.click:
                        alertDialog.dismiss();
                        scrolltype = 2;
                        callPhone(phoneSelectAdapter.getData().get(position).getPhonenum());
                        break;

                }
            }
        });
    }

    /*无网络*/
    @Override
    public void doNoNetSomething() {
        LogUtils.d("whatnetnonet");
        mStateView.showRetry();
    }


    private void alertareaend() {
        CityConfig cityConfig = new CityConfig.Builder()
                .confirTextColor("#1E90FF")
                .setCityWheelType(CityConfig.WheelType.PRO_CITY)
                .provinceCyclic(false)
                .cancelText("全国")
                .cityCyclic(false)
                .districtCyclic(false)
                .cancelTextColor("#1E90FF").build();
        mPickerend.setConfig(cityConfig);

        mPickerend.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                endctext = city.getName();

                endPlace.setText(city.getName());
                jiehuocheliangsmart.autoRefresh();
            }

            @Override
            public void onCancel() {
                com.lljjcoder.style.citylist.Toast.ToastUtils.showLongToast(getActivity(), "已取消");
                endctext = enddeaufttext;
                endPlace.setText("全国");
                jiehuocheliangsmart.autoRefresh();
            }
        });

        mPickerend.showCityPicker();
    }

    private void alertareastrat() {
        CityConfig cityConfig = new CityConfig.Builder()
                .setCityWheelType(CityConfig.WheelType.PRO_CITY)
                .confirTextColor("#1E90FF")
                .cancelText("全国")
                .provinceCyclic(false)
                .cityCyclic(false)
                .districtCyclic(false)
                .cancelTextColor("#1E90FF").build();
        mPickerstart.setConfig(cityConfig);

        mPickerstart.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                starttext = city.getName();
                startPlace.setText(city.getName());
                jiehuocheliangsmart.autoRefresh();
            }

            @Override
            public void onCancel() {
                com.lljjcoder.style.citylist.Toast.ToastUtils.showLongToast(getActivity(), "已取消");
                starttext = startdefaulttext;
                startPlace.setText("全国");
                jiehuocheliangsmart.autoRefresh();
            }
        });

        mPickerstart.showCityPicker();
    }

    @OnClick({R.id.search_start, R.id.search_end, R.id.search_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_start:
                darkenBackground(0.3f);
                searchStart.setTextColor(getActivity().getColor(R.color.selectareacolor));
                popstartwindow.showAsDropDown(showSearch);
                break;
            case R.id.search_end:
                darkenBackground(0.3f);
                searchEnd.setTextColor(getActivity().getColor(R.color.selectareacolor));
                popendwindow.showAsDropDown(showSearch);
                break;
            case R.id.search_more:
                darkenBackground(0.3f);
                searchMore.setTextColor(getActivity().getColor(R.color.selectareacolor));
                popsearch.showAsDropDown(showSearch);
                break;
        }
    }


    private void initArea() {
        context = getActivity();
        initPopStartWindow();
        initPopEndWindow();
        initPopSearchWindow();

        if (SPUtils.getAccounId(context) != 0) {
            initPrivice(0);
            initPrivice(1);
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        if (timer != null) {
            Log.d("定时器", "取消onstop");
            timer.cancel();
            typejiazai = 1;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (popstartwindow != null) {
            popstartwindow.dismiss();
        }

        if (popendwindow != null) {
            popendwindow.dismiss();
        }

        if (popsearch != null) {
            popsearch.dismiss();
        }

        if (timer != null) {
            Log.d("定时器", "取消onDestroy");
            timer.cancel();
            timer = null;
            typejiazai = 1;
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (getUserVisibleHint()) {
            isVisibleshow = true;
        } else {
            isVisibleshow = false;
        }

        if (isVisibleshow) {
            timerTest();
            Log.d("定时器", "取消Unvisible");
            typejiazai++;


        } else {
            if (timer != null) {
                Log.d("定时器", "取消onUnvisible");
                timer.cancel();
                typejiazai = 1;
            }
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Update_car:
                    if (itemAdapter.getData() != null) {
                        if (itemAdapter.getData().size() > 0) {
//                            int id = itemAdapter.getData().get(itemAdapter.getData().size() - 1).getId();
                            int id = itemAdapter.getData().get(0).getId();
                            initDataRecyclerview_New_Add(startCode, endCode, searchinfo, startProCode, endProCode, id);
                        }

                    }

                    break;
            }
        }
    };

    private void initDataRecyclerview_New_Add
            (String setoutcity, String destinationcity, String keysWord, String setoutprovince, String destinationprovince, int maxId) {
        OkGo.<String>get(Look_LianWang_New)

//                .params("id", SPUtils.getAccounId(getActivity()))
//                .params("pageNum", pagernum)
                .params("maxId", maxId)
                .params("setoutprovince", setoutprovince)
                .params("setoutcity", setoutcity)
                .params("destinationprovince", destinationprovince)
                .params("destinationcity", destinationcity)
                .params("keysWord", keysWord)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LianWangNewBean shipperPublishedBean = GsonUtil.parseJsonWithGson(response.body(), LianWangNewBean.class);
                        if (shipperPublishedBean.getData() != null) {
//                            int pageNum = shipperPublishedBean.getData().getPageNum();
//                            int pages = shipperPublishedBean.getData().getPages();
                            if (shipperPublishedBean.getCode().equals("0")) {

//                                if (shipperPublishedBean.getData().size() > 0) {
//                                    int PushCount = MaxPushCount;
//                                    if (shipperPublishedBean.getData().size() < MaxPushCount) {
//                                        PushCount = shipperPublishedBean.getData().size();
//                                    }
//
//                                    for (int i = 0; i < PushCount; i++) {
//                                        List<LianWangNewBean.DataBean> dataBeanList    = new ArrayList<>();
//                                        LianWangNewBean.DataBean dataBean = shipperPublishedBean.getData().get(i);
//
//                                        dataBeanList.add(dataBean);
//                                        itemAdapter.addData(0,dataBeanList);
//                                        jiehuocheliangrecy.smoothScrollToPosition(0);

                                if (shipperPublishedBean.getData() != null) {
                                    if (shipperPublishedBean.getData().size() > 0) {
                                        int PushCount = MaxPushCount;
                                        if (shipperPublishedBean.getData().size() < MaxPushCount) {
                                            PushCount = shipperPublishedBean.getData().size();
                                        }

                                        for (int i = 0; i < PushCount; i++) {
                                            List<LianWangNewBean.DataBean> dataBeanList = new ArrayList<>();
                                            LianWangNewBean.DataBean resultBean = shipperPublishedBean.getData().get(i);

                                            dataBeanList.add(resultBean);
                                            itemAdapter.addData(0, dataBeanList);

                                            if (scrolltype == 1) {
                                                if (alertDialog != null) {
                                                    if (!alertDialog.isShowing()) {
                                                        long currentTimeMillis = System.currentTimeMillis();
                                                        if (currentTimeMillis - start > 2000) {
                                                            jiehuocheliangrecy.smoothScrollToPosition(0);
                                                        }
                                                    }
                                                } else {
                                                    long currentTimeMillis = System.currentTimeMillis();
                                                    if (currentTimeMillis - start > 2000) {
                                                        jiehuocheliangrecy.smoothScrollToPosition(0);
                                                    }
                                                }


                                            } else if (scrolltype == 0) {
                                                jiehuocheliangrecy.smoothScrollToPosition(0);
                                            }

//                                            jiehuocheliangrecy.smoothScrollToPosition(0);

                                        }
                                    }
                                }


//                                if (pageNum == 1) {
//                                    itemAdapter.setNewData(shipperPublishedBean.getData().getResult());
//                                } else if (pageNum <= pages) {
//                                    itemAdapter.addData(shipperPublishedBean.getData().getResult());
//                                } else {
//                                    itemAdapter.loadMoreEnd();
//                                }

                            } else {
                                itemAdapter.loadMoreFail();
                            }

                        }
                        mStateView.showContent();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mStateView.showRetry();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void timerTest() {
        timer = new Timer();
        Log.d("定时器", "开始a");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = Update_car;
                mHandler.sendMessage(message);
            }//每隔10秒使用handler发送一下消息,也就是每隔10秒执行一次,一直重复执行
        }, 0, SecondTest);
    }

    private void initPopSearchWindow(
    ) {
        View contentView = View.inflate(getActivity(), R.layout.alert_find_something, null);
        EditText searchedit = (EditText) contentView.findViewById(R.id.find_search);

        TextView cancle = (TextView) contentView.findViewById(R.id.seach_clear);
        TextView ok = (TextView) contentView.findViewById(R.id.search_confirm);

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (searchedit.length() > 0) {
                    searchedit.setText("");
                    searchinfo = "";
                } else {
                    searchinfo = "";
                }
                pagernum = 1;
                jiehuocheliangsmart.autoRefresh();
//                searchContent(startCode, endCode, searchinfo);

                searchMore.setTextColor(getActivity().getColor(R.color.bottom_normal_text));

                popsearch.dismiss();
            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (searchedit.length() > 0) {
                    searchinfo = searchedit.getText().toString().trim();
                    pagernum = 1;
//                    searchContent(startCode, endCode, searchinfo);
                    jiehuocheliangsmart.autoRefresh();
                    popsearch.dismiss();
                } else {
                    Toast.makeText(getActivity(), "请输入搜索内容", Toast.LENGTH_SHORT).show();
                }

            }
        });


        popsearch = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );


        // 设置PopupWindow是否能响应外部点击事件
        popsearch.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        popsearch.setTouchable(true);

        popsearch.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        popsearch.setAnimationStyle(R.style.Popupwindow);

        popsearch.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (searchedit.length() < 1) {
                    searchMore.setTextColor(getActivity().getColor(R.color.bottom_normal_text));
                }
                darkenBackground(1f);
            }
        });

        popsearch.setContentView(contentView);
//        darkenBackground(0.3f);


    }


    private void darkenBackground(Float alpha) {
        if (alpha < 0 || alpha > 1) {
            return;
        }
        WindowManager.LayoutParams windowLP = getActivity().getWindow().getAttributes();
        windowLP.alpha = alpha;
        if (alpha == 1) {
            //不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        } else {
            //此行代码主要是解决在华为手机上半透明效果无效的bug
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        }
        getActivity().getWindow().setAttributes(windowLP);

    }

    private void searchContent(String startCode, String endCode, String searchinfo, String setoutprovince, String destinationprovince) {
        LogUtils.d("AAAAAAAAA" + startCode + "," + endCode + "," + searchinfo + "," + setoutprovince + "," + destinationprovince);
        initDataRecyclerview(startCode, endCode, searchinfo, setoutprovince, destinationprovince);
    }

    private void initPrivice(int type) {
        OkGo.<String>get(Area_Provice)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Selectareabean selectareabean = GsonUtil.parseJsonWithGson(response.body(), Selectareabean.class);
                        if (selectareabean.getCode().equals("0")) {

                            if (type == 0) {
                                List<Selectareabean.DataBean> dataStart = selectareabean.getData();
                                for (int i = 0; i < dataStart.size(); i++) {
                                    dataStart.get(i).setSelectcount(0);
                                }
                                privicestartAdapter.setNewData(dataStart);
                            } else if (type == 1) {
                                List<Selectareabean.DataBean> dataEnd = selectareabean.getData();
                                for (int i = 0; i < dataEnd.size(); i++) {
                                    dataEnd.get(i).setSelectcount(1);
                                }
                                priviceendAdapter.setNewData(dataEnd);
                            }


                        }

                    }
                });
    }


    private void initPopEndWindow() {
        View contentView = View.inflate(context, R.layout.alertselectonlinewindowtwo, null);
        RecyclerView scrollProvice = (RecyclerView) contentView.findViewById(R.id.scroll_provice_start);
        RecyclerView scrollCity = (RecyclerView) contentView.findViewById(R.id.scroll_city_start);
        TextView cancle = (TextView) contentView.findViewById(R.id.search_clear);
        TextView ok = (TextView) contentView.findViewById(R.id.search_confirm);


        popendwindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );


        // 设置PopupWindow是否能响应外部点击事件
        popendwindow.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        popendwindow.setTouchable(true);
        popendwindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popendwindow.setAnimationStyle(R.style.Popupwindow);

        popendwindow.setContentView(contentView);

        popendwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);


            }
        });

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                for (int i = 0; i < priviceendAdapter.getData().size(); i++) {
                    if (priviceendAdapter.getData().get(i).getSelect()) {
                        priviceendAdapter.getData().get(i).setSelect(false);
                        priviceendAdapter.notifyItemChanged(i);
                    }
                }
                cityendAdapter.setNewData(null);

                priviceendselectcount = 0;
                cityendselectcount = 0;
                endProCode = "";

                endCode = "";
                pagernum = 1;
                jiehuocheliangsmart.autoRefresh();
                searchEnd.setTextColor(getActivity().getColor(R.color.bottom_normal_text));
                popendwindow.dismiss();
            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cityendselectcount > 0) {

                    for (int i = 0; i < priviceendAdapter.getData().size(); i++) {
                        if (priviceendAdapter.getData().get(i).getSelect()) {
                            endProCode = priviceendAdapter.getData().get(i).getSname();
                        }
                    }

                    for (int i = 0, j = 0; i < cityendAdapter.getData().size(); i++) {
                        if (cityendAdapter.getData().get(i).getSelect()) {
                            if (j == 0) {
                                endCode = cityendAdapter.getData().get(i).getSname();
                                j++;
                            } else {
                                endCode += "," + cityendAdapter.getData().get(i).getSname();
                            }
                        }
                    }
                    pagernum = 1;
                    jiehuocheliangsmart.autoRefresh();
                    popendwindow.dismiss();
                }

//                注释掉可以是数据更精确
//                else if (priviceendpre > -1) {
//                    endProCode = priviceendAdapter.getData().get(priviceendpre).getSname();
//                    pagernum = 1;
//                    jiehuocheliangsmart.autoRefresh();
//                    popendwindow.dismiss();
//                    Log.d("TagArea", "pri:  " + String.valueOf(priviceendpre) + "    city:   " + String.valueOf(cityselectcount));
//                }

                else {
                    Toast.makeText(getActivity(), "请选择城市", Toast.LENGTH_SHORT).show();
                    Log.d("TagArea", "pri:  " + String.valueOf(priviceendpre) + "    city:   " + String.valueOf(cityselectcount));
                }
            }
        });


        priviceendAdapter = new AreaSelectItemEndAdapter();
        cityendAdapter = new AreaCitySelectItemAdapter();


        scrollProvice.setLayoutManager(new LinearLayoutManager(getActivity()));
        scrollProvice.setAdapter(priviceendAdapter);

        scrollCity.setLayoutManager(new LinearLayoutManager(getActivity()));
        scrollCity.setAdapter(cityendAdapter);


        priviceendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (priviceendAdapter.getData().get(0).getSelectcount() == 1) {
                    boolean select = priviceendAdapter.getData().get(position).getSelect();
                    priviceendAdapter.getData().get(position).setSelect(!select);
                    priviceendAdapter.notifyItemChanged(position);
                    if (select == false) {
                        cityendselectcount = 0;
                        initCity(priviceendAdapter.getData().get(position).getCode(), 1);
                        if (priviceendpre != -1) {
                            priviceendAdapter.getData().get(priviceendpre).setSelect(false);
                            priviceendAdapter.notifyItemChanged(priviceendpre);
                        }
                        priviceendpre = position;

                    } else {
                        cityendAdapter.setNewData(null);
                        priviceendpre = -1;
                    }


                }


            }
        });


        cityendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                boolean select = cityendAdapter.getData().get(position).getSelect();

                if (select == false) {
                    cityendselectcount++;
                    cityendAdapter.getData().get(position).setSelect(!select);
                    cityendAdapter.notifyItemChanged(position);
                } else {
                    cityendselectcount--;
                    cityendAdapter.getData().get(position).setSelect(!select);
                    cityendAdapter.notifyItemChanged(position);
                }
            }
        });


//        darkenBackground(0.3f);


    }

    /*type=0 起始地,type=1 目的地*/

    private void initCity(String provicecode, int type) {
        OkGo.<String>get(Area_City)
                .params("provinceCode", provicecode)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Selectareabean selectareabean = GsonUtil.parseJsonWithGson(response.body(), Selectareabean.class);
                        if (selectareabean.getCode().equals("0")) {
                            if (type == 0) {
                                citystartAdapter.setNewData(selectareabean.getData());
                            } else if (type == 1) {
                                cityendAdapter.setNewData(selectareabean.getData());
                            }
                        }

                    }
                });
    }

    private void initPopStartWindow() {
        View contentView = View.inflate(context, R.layout.alertselectonlinewindow, null);
        RecyclerView scrollProvice = (RecyclerView) contentView.findViewById(R.id.scroll_provice_start);
        RecyclerView scrollCity = (RecyclerView) contentView.findViewById(R.id.scroll_city_start);
        TextView cancle = (TextView) contentView.findViewById(R.id.search_clear);
        TextView ok = (TextView) contentView.findViewById(R.id.search_confirm);


        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < privicestartAdapter.getData().size(); i++) {
                    if (privicestartAdapter.getData().get(i).getSelect()) {
                        privicestartAdapter.getData().get(i).setSelect(false);
                        privicestartAdapter.notifyItemChanged(i);
                        break;
                    }
                }
                citystartAdapter.setNewData(null);

                priviceselectcount = 0;
                cityselectcount = 0;

                startCode = "";
                startProCode = "";
                pagernum = 1;
                jiehuocheliangsmart.autoRefresh();

                searchStart.setTextColor(getActivity().getColor(R.color.bottom_normal_text));


                popstartwindow.dismiss();

            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cityselectcount > 0) {

                    for (int i = 0; i < privicestartAdapter.getData().size(); i++) {
                        if (privicestartAdapter.getData().get(i).getSelect()) {
                            startProCode = privicestartAdapter.getData().get(i).getSname();
                            break;
                        }
                    }

                    for (int i = 0, j = 0; i < citystartAdapter.getData().size(); i++) {
                        if (citystartAdapter.getData().get(i).getSelect()) {
                            if (j == 0) {
                                startCode = citystartAdapter.getData().get(i).getSname();
                                j++;
                            } else {
                                startCode += "," + citystartAdapter.getData().get(i).getSname();
                            }
                        }
                    }
                    pagernum = 1;
                    jiehuocheliangsmart.autoRefresh();
                    popstartwindow.dismiss();
                }
                //                注释掉可以是数据更精确
//                else if (privicepre > -1) {
//                    startProCode = privicestartAdapter.getData().get(privicepre).getSname();
//                    pagernum = 1;
//                    jiehuocheliangsmart.autoRefresh();
//                    popstartwindow.dismiss();
//                }
                else {
                    Toast.makeText(getActivity(), "请选择城市", Toast.LENGTH_SHORT).show();
//                    Log.d("TagArea", "pri:  " + String.valueOf(privicepre) + "    city:   " + String.valueOf(cityselectcount));
                }

            }
        });


        privicestartAdapter = new AreaSelectItemAdapter();
        citystartAdapter = new AreaCitySelectItemAdapter();


        scrollProvice.setLayoutManager(new LinearLayoutManager(getActivity()));
        scrollProvice.setAdapter(privicestartAdapter);

        scrollCity.setLayoutManager(new LinearLayoutManager(getActivity()));
        scrollCity.setAdapter(citystartAdapter);


        privicestartAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {


                if (privicestartAdapter.getData().get(0).getSelectcount() == 0) {
                    boolean select = privicestartAdapter.getData().get(position).getSelect();
                    privicestartAdapter.getData().get(position).setSelect(!select);
                    privicestartAdapter.notifyItemChanged(position);
                    if (select == false) {
                        cityselectcount = 0;
                        initCity(privicestartAdapter.getData().get(position).getCode(), 0);
                        if (privicepre != -1) {
                            privicestartAdapter.getData().get(privicepre).setSelect(false);
                            privicestartAdapter.notifyItemChanged(privicepre);
                        }
                        privicepre = position;

                    } else {
                        citystartAdapter.setNewData(null);
                        privicepre = -1;
                    }


                }


            }
        });


        citystartAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                boolean select = citystartAdapter.getData().get(position).getSelect();

                if (select == false) {
                    cityselectcount++;
                    citystartAdapter.getData().get(position).setSelect(!select);
                    citystartAdapter.notifyItemChanged(position);
                } else {
                    cityselectcount--;
                    citystartAdapter.getData().get(position).setSelect(!select);
                    citystartAdapter.notifyItemChanged(position);
                }


            }
        });

        popstartwindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );


        // 设置PopupWindow是否能响应外部点击事件
        popstartwindow.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        popstartwindow.setTouchable(true);
        popstartwindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        popstartwindow.setAnimationStyle(R.style.Popupwindow);
        popstartwindow.setContentView(contentView);

        popstartwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);

            }
        });
    }


}
